package com.hcc.flow.server.common.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author Administrator
 *
 * @version 创建时间：2019年8月8日下午4:56:55
 *类说明:利用spring httpTemplate进行接口请求
 */
public class HttpUtils {
	
	/**
	 * 以json的方式 post请求
	 * @param url
	 * @param postParameters
	 * @return
	 */
    public static JSONObject post(String url, JSONObject postParameters){
    	if(StringUtilsV2.isBlank(url)) {
    		return null;
    	}
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<JSONObject> r = new HttpEntity<>(postParameters, headers);
		return new RestTemplate().postForEntity(url,r,JSONObject.class).getBody();
    }
    
    /**
     * form方式的post请求
     * @param url
     * @param postParameters
     * @return
     */
    public static JSONObject post(String url, MultiValueMap<String, String> postParameters){
    	if(CollectionUtils.isEmpty(postParameters)) {
    		return null;
    	}
    	HttpHeaders headers=new HttpHeaders();
    		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    		ResponseEntity<JSONObject> response = new RestTemplate().postForEntity( url, new HttpEntity<>(postParameters, headers) , JSONObject.class );
    	return response.getBody();
    }
}
